import os
import requests

# 请求头
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 '
                  'Safari/537.36 Edg/127.0.0.0',
}

image_count = 0

current_page = 1

target_count = 100

while image_count < target_count:
    json_data = {
        'size': 24,
        'current': current_page,
        'sort': 0,
        'category': 0,
        'resolution': 0,
        'color': 0,
        'categoryId': 0,
        'ratio': 0,
    }

    try:
        res = requests.post('https://api.zzzmh.cn/v2/bz/v3/getData', headers=headers, json=json_data)
        data_list = res.json()['data']['list']

        for item in data_list:
            if image_count >= target_count:
                break
            try:
                res_img = requests.get(f"https://api.zzzmh.cn/v2/bz/v3/getUrl/{item['i']}29")
                with open(f'极简壁纸/image{image_count + 1}.jpg', 'wb') as file:
                    print(f"正在下载第 {image_count + 1} 张图片...")
                    file.write(res_img.content)
                image_count += 1
            except Exception as e:
                print(f"下载图片时出错: {e}")
    except Exception as e:
        print(f"请求数据时出错: {e}")

    current_page += 1

print(f"已成功下载 {image_count} 张图片。")
